package ms.server.api.crypto;

import ms.server.api.annotation.Decrypt;
import ms.server.api.exception.BusinessException;
import ms.server.api.util.RSAUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;

/**
 * 请求数据接收处理类<br>
 * <p>
 * 对加了@Decrypt的方法的数据进行解密操作<br>
 * <p>
 * 只对 @RequestBody 参数有效
 *
 * @Author ybc
 * @Date 2021/7/6 14:35
 */
@Slf4j
@ControllerAdvice(basePackages = "aed.server.api.controller")
public class DecryptRequestAdvice implements RequestBodyAdvice {

    private static final String charset = "UTF-8";

    @Value("${api.inner.private_key}")
    private String PRIVATE_KEY;

    @Override
    public boolean supports(MethodParameter methodParameter,
                            Type type,
                            Class<? extends HttpMessageConverter<?>> aClass) {
        return methodParameter.getMethod().isAnnotationPresent(Decrypt.class);
    }

    @SneakyThrows
    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage,
                                           MethodParameter methodParameter,
                                           Type type,
                                           Class<? extends HttpMessageConverter<?>> aClass) {
        try {
            log.info("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行解密");
            return new AedHttpInputMessage(httpInputMessage);
        } catch (Exception e) {
            log.error("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行解密出现异常：" + e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public Object afterBodyRead(Object body,
                                HttpInputMessage httpInputMessage,
                                MethodParameter methodParameter,
                                Type type,
                                Class<? extends HttpMessageConverter<?>> aClass) {
        return body;
    }

    @Override
    public Object handleEmptyBody(Object body,
                                  HttpInputMessage httpInputMessage,
                                  MethodParameter methodParameter,
                                  Type type,
                                  Class<? extends HttpMessageConverter<?>> aClass) {
        return body;
    }

    class AedHttpInputMessage implements HttpInputMessage {

        private HttpHeaders headers;

        private InputStream body;

        public AedHttpInputMessage(HttpInputMessage inputMessage) throws Exception {
            this.headers = inputMessage.getHeaders();
            String content = dealString(IOUtils.toString(inputMessage.getBody(), charset));
            this.body = IOUtils.toInputStream(RSAUtils.decryptDataOnJava(content, PRIVATE_KEY), charset);
        }

        @Override
        public InputStream getBody() throws IOException {
            return body;
        }

        @Override
        public HttpHeaders getHeaders() {
            return headers;
        }
    }

    /**
     * 请求的json数据处理获取加密数据
     *
     * @param requestData
     * @return
     */
    public String dealString(String requestData) {
        if (requestData != null && !requestData.equals("")) {
            String s = "{\"reqData\":";
            if (!requestData.startsWith(s)) {
                throw new BusinessException("参数【reqData】缺失异常！");
            } else {
                int closeLen = requestData.length() - 1;
                int openLen = "{\"reqData\":".length();
                String substring = StringUtils.substring(requestData, openLen, closeLen);
                return substring;
            }
        }
        return "";
    }

}
